package com.xiangyang.pos.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xiangyang.pos.R;
import com.xiangyang.pos.adapter.UserShoppingDataRecyclerViewAdapter;
import com.xiangyang.pos.bean.OrderErrorDataBean;
import com.xiangyang.pos.bean.UserShoppingDataBean;
import com.xiangyang.pos.constant.AppConstant;
import com.xiangyang.pos.http.HttpClient;
import com.xiangyang.pos.http.RequestParameters;
import com.xiangyang.pos.logger.Logger;
import com.xiangyang.pos.utils.SharedUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/19 0019.
 *
 * 用户输入手机号
 *
 * @author YeDalin
 *
 */

public class SettlementActivity extends Activity {

    private TextView tvAllMoney;
    private EditText etUserPhone;
    private Button bSureUser;
    private Button bCash;
    private Button bMove;
    private RecyclerView rvUserShoppingData;
    private TextView tvShoppingData;
    private TextView tvTime;
    private ProgressBar progressBar;
    private ImageView ivGoBack;

    private CircleImageView ivUserPhoto;

    private boolean isUser = false;

    private UserShoppingDataRecyclerViewAdapter adapter;
    private List<UserShoppingDataBean.UserShop> list = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement);
        initView();
//        initAdapter();
        setMyClick();
    }


    private void initView() {
        tvAllMoney = findViewById(R.id.tv_all_money);
        etUserPhone = findViewById(R.id.et_user_phone);
        bSureUser = findViewById(R.id.b_sure_user);
        bCash = findViewById(R.id.b_cash);
        bMove = findViewById(R.id.b_move);
        rvUserShoppingData = findViewById(R.id.rv_user_shopping_data);
        tvShoppingData = findViewById(R.id.tv_shopping_data);
        tvTime = findViewById(R.id.tv_time);
        progressBar = findViewById(R.id.progress_bar);
        ivGoBack = findViewById(R.id.iv_go_back);

        ivUserPhoto = findViewById(R.id.iv_user_photo);


        int all_money = SharedUtils.getIntPrefs(this, "all_money", -1);
        tvAllMoney.setText("￥" + all_money / 100.0);

    }

    //    初始化适配器
    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvUserShoppingData.setLayoutManager(manager);
        Logger.e("xxxxxxxxxxx", "****" + list.size());
        adapter = new UserShoppingDataRecyclerViewAdapter(list);
        rvUserShoppingData.setAdapter(adapter);
    }

    private void setMyClick() {
        bCash.setOnClickListener(listener);
        bMove.setOnClickListener(listener);
        bSureUser.setOnClickListener(listener);
        ivGoBack.setOnClickListener(listener);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.b_move:

                    getIsPhone();
                    SharedUtils.setStringPrefs(SettlementActivity.this, "user_phone", etUserPhone.getText().toString());
                    Intent intent1 = new Intent(SettlementActivity.this, ChoosePayActivity.class);
                    startActivityForResult(intent1,2002);

                    break;
                case R.id.b_cash:
                    getIsPhone();
                    SharedUtils.setStringPrefs(SettlementActivity.this, "out_on", "KX-Cash-" + getTime());
                    SharedUtils.setStringPrefs(SettlementActivity.this, "pmt_tag", "Cash");
                    SharedUtils.setStringPrefs(SettlementActivity.this, "user_phone", etUserPhone.getText().toString());
                    Intent intent = new Intent(SettlementActivity.this, ConfirmReceivablesActivity.class);
                    intent.putExtra("pay", 1);
                    startActivityForResult(intent,2000);
                    break;
                case R.id.b_sure_user:
                    if (isPhone()) {
                        etUserPhone.setFocusable(false);
                        getHttp();
                    } else {
                        etUserPhone.setFocusable(true);
                        etUserPhone.setFocusableInTouchMode(true);
                    }
                    break;
                case R.id.iv_go_back:
                    finish();
                    break;
            }
        }
    };


    private void getHttp() {
        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
//        final String USER_PHONE_URL = AppConstant.POS_URL + "/Pay/An/records/u=" + apiToken;

        final String USER_PHONE_URL=AppConstant.POS_URL+"/Pay/An/records"+"/u="+UserTOKEN;

        progressBar.setVisibility(View.VISIBLE);

        HttpClient httpClient = new HttpClient();
        httpClient.post(USER_PHONE_URL, getUserPhone(), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {

                progressBar.setVisibility(View.GONE);
                if (!result.equals("Error")) {
                    Logger.e("xxxx", "result = " + result);
                    Gson gson = new Gson();
                    UserShoppingDataBean bean = gson.fromJson(result, UserShoppingDataBean.class);

                    if(bean!=null){
                        if(bean.getStatus()==1){

                            for (int i = 0; i < bean.getData().getContent().size(); i++) {
                                list.addAll(bean.getData().getContent().get(i).getShopgoods());
                            }


                            initAdapter();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            long l = System.currentTimeMillis();
                            String format = sdf.format(new Date(l));
                            tvTime.setText("消费记录\n" + format);

                            tvTime.setVisibility(View.VISIBLE);
                            rvUserShoppingData.setVisibility(View.VISIBLE);
                        }else {
                            tvShoppingData.setVisibility(View.VISIBLE);
                        }
                    }


                   /* SharedUtils.setStringPrefs(SettlementActivity.this, "userId", bean.getUserId());

                    if (bean != null) {
                        if (bean.getStatus() == 1) {
                            if (bean.getMsg() == null) {

                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                long l = Long.valueOf(bean.getData().get(0).getCreate_time());
                                String format = sdf.format(new Date(l * 1000));
                                tvTime.setText("消费记录\n" + format);

                                tvTime.setVisibility(View.VISIBLE);

                                rvUserShoppingData.setVisibility(View.VISIBLE);
                                list = bean.getData();

                                initAdapter();

                                isUser = true;
                            } else {
                                tvShoppingData.setVisibility(View.VISIBLE);
                                isUser = true;
                            }
                        } else {
                            tvShoppingData.setVisibility(View.VISIBLE);
                            isUser = true;
                        }
                    }*/

                } else {
                    Toast.makeText(SettlementActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //    上传手机号
    private RequestParameters getUserPhone() {
        RequestParameters parameters = new RequestParameters();
        parameters.put("phone", etUserPhone.getText().toString());
        return parameters;
    }

    //    判断手机号是否为11位数
    private boolean isPhone() {
        if (etUserPhone.getText().toString().length() == 11) {
            SharedUtils.setStringPrefs(this, "user_phone", etUserPhone.getText().toString());
            return true;
        }
        Toast.makeText(SettlementActivity.this, "手机号应该为11位数", Toast.LENGTH_SHORT).show();
        return false;
    }

    private void getIsPhone(){
        if(etUserPhone.getText().toString().length()==11){
            getHttp();
        }else {
            SharedUtils.setStringPrefs(SettlementActivity.this, "userId", "");
        }
    }

    //    获取时间戳
    private String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2000){
            setResult(2000,data);
            finish();
        }else if(requestCode==2002){
            if(data!=null){
                List<OrderErrorDataBean.OrderErrorData> order=(List<OrderErrorDataBean.OrderErrorData>)data.getSerializableExtra("list");
                Logger.e("xxxx","商品实时数量1= "+order.get(0).getNum());
                setResult(2000,data);
                finish();
            }
        }
    }
}
